package org.example.deadletter;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.util.MapStringToMapUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 死信队列中消息的消费
 *
 *@ClassName: DeadLetterReceiver
 *@Author: CJ
 *@Date: 2021-9-25 20:17
 */
@Slf4j
@Component
public class DeadLetterReceiver {

    // 用来测试：队列达到最大长度时，没有被挤掉的消要手动确认签收，挤掉的进入死信队列，并取消手动确认
    @RabbitListener(queues = {"dead.letter.deadletter.queuea"})
    @RabbitHandler
    public void deadLetterConsumer1(@NotNull Message message, @NotNull Channel channel) {
        String msg = message.toString();
        String[] msgArray = msg.split("'");
        Map<String, String> msgMap = MapStringToMapUtil.getStringMap(msgArray[1].trim());
        String messageId = msgMap.get("messageId");
        String messageData = msgMap.get("messageData");
        String createTime = msgMap.get("createTime");
        log.info("死信队列接收到的消息为：" + "MyAckReceiver  messageId:" + messageId + "  messageData:" + messageData + "  createTime:" + createTime);
        log.info("消费的主题消息来自：" + message.getMessageProperties().getConsumerQueue());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            log.info("死信队列中消息的消费失败", e);
            e.printStackTrace();
        }
    }

    @RabbitListener(queues = {"dead.letter.deadletter.queueb"})
    @RabbitHandler
    public void deadLetterConsumer2(@NotNull Message message, @NotNull Channel channel) {
        String msg = message.toString();
        String[] msgArray = msg.split("'");
        Map<String, String> msgMap = MapStringToMapUtil.getStringMap(msgArray[1].trim());
        String messageId = msgMap.get("messageId");
        String messageData = msgMap.get("messageData");
        String createTime = msgMap.get("createTime");
        log.info("死信队列接收到的消息为：" + "MyAckReceiver  messageId:" + messageId + "  messageData:" + messageData + "  createTime:" + createTime);
        log.info("消费的主题消息来自：" + message.getMessageProperties().getConsumerQueue());
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (IOException e) {
            log.info("死信队列中消息的消费失败", e);
            e.printStackTrace();
        }
    }
}
